package com.cdty.chess.service.impl;

import com.cdty.chess.model.Cuser;
import com.cdty.chess.service.LoginService;
import com.cdty.chess.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    NamedParameterJdbcTemplate template;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Map<String,Object> login(Cuser cuser) {
        Map<String,Object> reResult = new HashMap<>();
        String sql = """
                    SELECT * from cuser c where uname =:uname and is_use = true
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        if(StringUtils.hasText(cuser.getUname())){
            param.addValue("uname",cuser.getUname());
        }
        List<Cuser> result = template.query(sql, param, new BeanPropertyRowMapper<>(Cuser.class));
        if(result!=null && result.size()==1&&passwordEncoder.matches(cuser.getPassword(), result.get(0).getPassword())){
            String newJti = UUID.randomUUID().toString();
            param.addValue("jti",newJti);
            param.addValue("uid",result.get(0).getUid());
            String updateSql = "UPDATE cuser SET current_jti = :jti WHERE uid = :uid";
            template.update(updateSql,param);

            reResult.put("success",true);
            reResult.put("data",result.get(0));
            String token = TokenUtils.genToken(result.get(0).getUid().toString(), newJti);
            reResult.put("token",token);
        }else{
            reResult.put("success",false);
            reResult.put("data","登录失败,请验证用户名和密码");
            reResult.put("token",null);
        }

        return reResult;
    }


}
